<template>
	<view class="container">
		<view class="hd">
			<text class="hd-title">身份认证</text>
			<text class="hd-desc">填写真实有效的姓名、身份证号码进行实名认证</text>
		</view>

		<view class="form">
			<u--form :model="formData" :rules="rules" ref="form">
				<view class="form-item">
					<u-form-item prop="username"><u--input border="bottom" v-model="formData.username" clearable placeholder="姓名"></u--input></u-form-item>
				</view>
				<view class="form-item">
					<u-form-item prop="idCard"><u--input border="bottom" v-model="formData.idCard" clearable placeholder="身份证号码" type="idcard"></u--input></u-form-item>
				</view>
			</u--form>
		</view>
		<view class="btn button-primary" @tap="submit">开始人脸识别</view>
	</view>
</template>

<script>
export default {
	name: 'login',
	data() {
		return {
			formData: {
				username: '',
				idCard: ''
			},
			rules: {
				username: {
					type: 'string',
					required: true,
					message: '请填写有效的姓名',
					trigger: ['blur', 'change']
				},
				idCard: {
					type: 'string',
					required: true,
					message: '请填写有效的身份证号码',
					trigger: ['blur', 'change'],
					pattern: /^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/
				}
			}
		};
	},
	onLoad() {

	},
	onReady() {
		this.$refs.form.setRules(this.rules);
	},
	methods: {
		onAuth() {
			uni.$u.toast('认证成功');
			uni.$u.route({
				type: 'switchTab',
				url: '/pages/index/index'
			});
		},

		submit(e) {
			var that = this;
			this.$refs.form.validate().then(res => {
				let { username, idCard } = this.formData;
				wx.checkIsSupportFacialRecognition({
					checkAliveType: 2,
					success(res) {
						if (res.errCode === 0 || res.errMsg === 'checkIsSupportFacialRecognition:ok') {
							//调用人脸识别
							that.startface(username.replace(/(^\s*)|(\s*)$/g, ''), idCard);
							return;
						}
						uni.$u.toast('微信版本过低，暂时无法使用此功能，请升级微信最新版本');
					},
					fail: err => {
						uni.$u.toast('微信版本过低，暂时无法使用此功能，请升级微信最新版本');
					}
				});
			});
		},
		startface(name, idCardNumber) {
			var that = this;
			wx.startFacialRecognitionVerify({
				name,
				idCardNumber,
				checkAliveType: 2, //屏幕闪烁(人脸核验的交互方式，默认0,读数字)
				success(res) {
					// uni.showLoading({
					// 	title: '跳转中...',
					// 	mask: true
					// });
					var errCode = res.errCode;
					if (errCode == 0) {
						// uni.hideLoading();
						that.onAuth();
					} else {
						uni.$u.toast('检测失败，请联系管理员');
					}
				},
				fail: err => {
					uni.$u.toast('请保持光线充足，面部正对手机，且无遮挡');
				}
			});
		}
	}
};
</script>
<style scoped lang="scss">
.container {
	background-color: #ffffff;
	.hd {
		padding: 64rpx 32rpx;
		display: flex;
		flex-direction: column;
		.hd-title {
			font-size: 44rpx;
			font-weight: bold;
			margin-bottom: 16rpx;
		}
		.hd-desc {
			color: #86909c;
		}
	}
	.form {
		padding: 16rpx 32rpx;
		.form-item {
			min-height: 140rpx;
		}
	}
	.btn {
		margin: 0 auto;
		width: 668rpx;
		margin-top: 86rpx;
	}
}
</style>
